package testJdk.lambda;

import org.junit.Test;

import java.util.Comparator;
import java.util.TreeSet;
import java.util.function.Consumer;

/**
 * @ClassName : learn_jdk.lambda.LearnLambda
 * @Description : 类描述
 * Created by cyd on 2021-03-31 23:04:50
 */
public class LearnLambda {

    class MyRunnable implements Runnable {

        @Override
        public void run() {
            int i = 0;
            System.out.println("hello " + i);

        }
    }

    @Test
    public void test() {
        MyRunnable myRunnable = new MyRunnable();
        myRunnable.run();
    }

    /**
     * 测试正常执行的匿名Runnable实例的run方法
     */
    @Test
    public void test1() {
        int i = 0;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello " + i);
            }
        };
        runnable.run();
    }

    /**
     * 体验lambda的使用，更简洁优雅
     */
    @Test
    public void test01() {
        int i = 1;
        Runnable runnable = () -> {
            System.out.println(i);
        };
        runnable.run();
    }

    @Test
    public void test001() {
        int i = 2;
        Runnable runnable = System.out::println;
    }

    /**
     * Consumer接口用于预先定义一个函数，它的实例可以用accept方法直接调用
     */
    class MyConsumer implements Consumer<String> {

        @Override
        public void accept(String s) {
            System.out.println(s);
        }
    }

    @Test
    public void test2() {
        // 正常使用
        MyConsumer com = new MyConsumer();
        com.accept("123   hello");
    }

    @Test
    public void test02() {
        // 匿名使用
        Consumer<String> com = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        com.accept("123   hello");
    }

    @Test
    public void test002() {
        // lambda表达式使用
        Consumer<String> com = x -> {
            System.out.println(x);
        };
        com.accept("123   hello");
    }

    @Test
    public void test0002() {
        // lambda表达式使用
        Consumer<String> com = System.out::println;
        com.accept("123   hello");
    }

    @Test
    public void test3() {
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };
        TreeSet<Integer> treeSet = new TreeSet<>(comparator);
    }

    @Test
    public void test004() {
        Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);

        TreeSet<Integer> treeSet = new TreeSet<>(comparator);
    }
}
